import java.io.BufferedReader;
import java.io.InputStreamReader;

import java.net.URI;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Vector;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class QueryProcess {
  public static String LINE_BREAK = "******************************";

  enum PolarityValue {
    POSITIVE, NEGATIVE, NEUTRAL,
  }

  // comment id as key, Comment object as value
  private HashMap<String, Comment> comments = new HashMap<String, Comment>();
  private HashMap<String, Comment> modComments = new HashMap<String, Comment>();
  private HashSet<String> issues_ = new HashSet<String>();
  private static QueryProcess qp_;
  private static URI uri = null;
  private static URI appuri = null;
  private static URI moduri = null;
  
  private QueryProcess() {
   
  }
  
  public void initialize(String parent, String appinion, String moderator){
	  try {
		  //"http://www.cs.cornell.edu/~qsh2/SA/apr_parent.xml"
	    	uri = new URI(parent);
	    	//"http://www.cs.cornell.edu/~qsh2/SA/apr_app.xml"
	    	appuri = new URI(appinion);
	    	// "http://www.cs.cornell.edu/~qsh2/SA/moderator.xml"
	    	moduri = new URI(moderator);
	      parseLaw(uri.toString());
	      parseAppinion(appuri.toString());
	      parseModerator(moduri.toString());
	    } catch (Exception e) {
	      e.printStackTrace();
	    }
  }
  
  public static void clean(){
	qp_ = null;  
  }
  
  public static QueryProcess getInstance() {
    if (qp_ == null) {
      qp_ = new QueryProcess();
    }
    return qp_;
  }

  public static void main(String[] args) throws Exception {
    ArrayList<String> results = new ArrayList<String>();
    QueryProcess qp = QueryProcess.getInstance();
    
//    results = qp.showOverallOpinionStats();
//    results = qp.showOverallCommentStats();
    
//    results = qp.showOpinionsWithPolarity(PolarityValue.POSITIVE);
//    results = qp.showOpinionsWithPolarity(PolarityValue.NEGATIVE);
//    results = qp.showOpinionsWithPolarity(PolarityValue.NEUTRAL);
//
//    results = qp.showCommentsWithPolarity(PolarityValue.POSITIVE);
//    results = qp.showCommentsWithPolarity(PolarityValue.NEGATIVE);
//    results = qp.showCommentsWithPolarity(PolarityValue.NEUTRAL);
//
//    results =  qp.opinionHolderStats();
//    results =  qp.showAuthorWiseCumulativePolarity();
//    results =  qp.showIssueWiseCumulativePolarity();
//    results = qp.showIssueWiseTopicList();
    
    
    
    ArrayList<String> issues = qp.getIssues();
    System.out.println(issues);
    System.out.println(issues.size());
    // Use the values returned by getIssues here.
    results = qp.getIssueWiseTopicList("peanut allergies");
    
    for (int i = 0; i < results.size(); ++i) {
      String t = results.get(i).replaceAll("[;]+", "\n");
      t = t.replaceAll("<br>", "\n");
      
     // System.out.println(t);
    }
  }
  
  public ArrayList<String> getIssues() {
    ArrayList<String> res = new ArrayList<String>();

    String[] issueArray = new String[20];
    issueArray = issues_.toArray(issueArray);
    
    for (int i = 0; i < issueArray.length; ++i) {
      if (issueArray[i] == null)
        break;
      res.add(issueArray[i]);
    }
    
    return res;
  }

  public ArrayList<String> getNegativeComments() {
    return showCommentsWithPolarity(PolarityValue.NEGATIVE);
  }

  public ArrayList<String> getNeutralComments() {
    return showCommentsWithPolarity(PolarityValue.NEUTRAL);
  }

  public ArrayList<String> getPositiveComments() {
    return showCommentsWithPolarity(PolarityValue.POSITIVE);
  }

  public ArrayList<String> getNegativeOpinions() {
    return showOpinionsWithPolarity(PolarityValue.NEGATIVE);
  }

  public ArrayList<String> getNeutralOpinions() {
    return showOpinionsWithPolarity(PolarityValue.NEUTRAL);
  }

  public ArrayList<String> getPositiveOpinions() {
    return showOpinionsWithPolarity(PolarityValue.POSITIVE);
  }

  public ArrayList<String> getModeratorNegativeComments() {

    Iterator<Map.Entry<String, Comment>> it = modComments.entrySet().iterator();
    ArrayList<String> sents = new ArrayList<String>();

    while (it.hasNext()) {
      Map.Entry<String, Comment> entry = it.next();
      Comment mcm = entry.getValue();

      String parentId = mcm.getParentId();

      if (!parentId.equals("0")) {

        Comment cm = comments.get(parentId);

        if (cm == null)
          cm = modComments.get(parentId);

        if (cm != null) {

          if (cm.isPolaritySet() && cm.getCumulativePolarity() < 0) {

            String sent = "<b>Author: </b>" + cm.getAuthor() + ";;"
                + "<b>Comment ID: </b>" + cm.getCommentID() + ";;"
                + "<b>Comment: </b>" + cm.getComment() + ";;;"
                + "<b><font color=\"Pastel Green\">" + mcm.getAuthor()
                + "</font></b>" + ";;" + "<b>Comment ID: </b>"
                + mcm.getCommentID() + ";;" + "<b>Comment: </b>"
                + mcm.getComment();

            sents.add(sent);

          }

        }

      }// else for parent != null

    }// while loop ends

    return sents;
  }

  public ArrayList<String> getModeratorPositiveComments() {

    Iterator<Map.Entry<String, Comment>> it = modComments.entrySet().iterator();
    ArrayList<String> sents = new ArrayList<String>();

    while (it.hasNext()) {
      Map.Entry<String, Comment> entry = it.next();
      Comment mcm = entry.getValue();

      String parentId = mcm.getParentId();

      if (!parentId.equals("0")) {

        Comment cm = comments.get(parentId);

        if (cm == null)
          cm = modComments.get(parentId);

        if (cm != null) {

          if (cm.isPolaritySet() && cm.getCumulativePolarity() > 0) {

            String sent = "<b>Author: </b>" + cm.getAuthor() + ";;"
                + "<b>Comment ID: </b>" + cm.getCommentID() + ";;"
                + "<b>Comment: </b>" + cm.getComment() + ";;;"
                + "<b><font color=\"Pastel Green\">" + mcm.getAuthor()
                + "</font></b>" + ";;" + "<b>Comment ID: </b>"
                + mcm.getCommentID() + ";;" + "<b>Comment: </b>"
                + mcm.getComment();

            sents.add(sent);

          }

        }

      }// if parent != null

    }// while loop ends

    return sents;

  }

  public ArrayList<String> getModeratorNeutralComments() {

    Iterator<Map.Entry<String, Comment>> it = modComments.entrySet().iterator();
    ArrayList<String> sents = new ArrayList<String>();

    while (it.hasNext()) {
      Map.Entry<String, Comment> entry = it.next();
      Comment mcm = entry.getValue();

      String parentId = mcm.getParentId();

      if (!parentId.equals("0")) {

        Comment cm = comments.get(parentId);

        if (cm == null)
          cm = modComments.get(parentId);

        if (cm != null) {

          if (cm.isPolaritySet() && cm.getCumulativePolarity() == 0) {

            String sent = "<b>Author: </b>" + cm.getAuthor() + ";;"
                + "<b>Comment ID: </b>" + cm.getCommentID() + ";;"
                + "<b>Comment: </b>" + cm.getComment() + ";;;"
                + "<b><font color=\"Pastel Green\">" + mcm.getAuthor()
                + "</font></b>" + ";;" + "<b>Comment ID: </b>"
                + mcm.getCommentID() + ";;" + "<b>Comment: </b>"
                + mcm.getComment();

            sents.add(sent);

          }

        }

      }// else for parent != null

    }// while loop ends

    return sents;

  }

  public int getModeratorTotalComment() {

    return modComments.size();
  }

  public void getModeratorCommentStats() {
    Iterator<Map.Entry<String, Comment>> it = modComments.entrySet().iterator();

    int positive = 0;
    int negative = 0;
    int neutral = 0;
    int untagged = 0;
    int toplevel = 0;
    int self = 0;
    int total = 0;

    while (it.hasNext()) {
      Map.Entry<String, Comment> entry = it.next();
      Comment mcm = entry.getValue();
      total++;

      String parentId = mcm.getParentId();
      if (parentId.equals("0")) {
        toplevel++;
        continue;
      }

      Comment cm = comments.get(parentId);

      if (cm == null) {
        // Try retrieving the parent from moderator comments.
        cm = modComments.get(parentId);

        // If still no result. Give up.
        if (cm == null) {
          System.out.println("ERROR: Moderator comment " + mcm.getCommentID()
              + ": Parent does not exist: " + mcm.getParentId());
          continue;
        }
      }

      if (!cm.isPolaritySet()) {
        untagged++;
      } else {
        if (cm.getCumulativePolarity() == 0) {
          neutral++;
        } else if (cm.getCumulativePolarity() < 0) {
          negative++;
        } else {
          positive++;
        }
      }
    }

    System.out.println("Moderator Comment Statistics:");
    System.out.println("Total: " + total);
    System.out.println("Top level: " + toplevel);
    System.out.println("Untagged: " + untagged);
    System.out.println("Negative: " + negative);
    System.out.println("Positive: " + positive);
    System.out.println("Neutral: " + neutral);
  }

  public ArrayList<String> getAuthorWiseCumulativePolarity() {
    ArrayList<String> authors = new ArrayList<String>();

    HashMap<String, CumulativePolarity> authorPolarityMap = new HashMap<String, CumulativePolarity>();

    Iterator<Map.Entry<String, Comment>> it = comments.entrySet().iterator();

    while (it.hasNext()) {
      Map.Entry<String, Comment> entry = it.next();
      Comment cm = entry.getValue();

      String author = cm.getAuthor();
      CumulativePolarity cp = authorPolarityMap.get(author);
      if (cp == null) {
        cp = new CumulativePolarity();
        authorPolarityMap.put(author, cp);
      }

      int p = cm.getCumulativePolarity();
      if (p > 0) {
        cp.addPositiveComment(0.0);
      } else if (p < 0) {
        cp.addNegativeComment(0.0);
      } else {
        cp.addNeutralComment();
      }

      /*
       * Vector<Polarity> pols = cm.getPolarities(); for (int i = 0; i <
       * pols.size(); ++i) { Polarity p = pols.get(i);
       * 
       * if (p.getValue() > 0) { cp.addPositiveComment(); } else if
       * (p.getValue() < 0) { cp.addNegativeComment(); } else if (p.getValue()
       * == 0) { cp.addNeutralComment(); } }
       */
    }

    Iterator<Map.Entry<String, CumulativePolarity>> ipm = authorPolarityMap
        .entrySet().iterator();
    int numPos = 0, numNeg = 0, numNeu = 0;
    while (ipm.hasNext()) {
      Map.Entry<String, CumulativePolarity> entry = ipm.next();
      CumulativePolarity ip = entry.getValue();

      StringBuffer author = new StringBuffer("Author: " + entry.getKey() + ";;");
      author.append("Cumulative: " + ip.getCumulative() + ";;");
      author.append("Positive: " + ip.numPositive + ";;");

      author.append("Negative: " + ip.numNegative + ";;");
      author.append("Neutral: " + ip.numNeutral);
      authors.add(author.toString());

      if (ip.getCumulative() > 0) {
        numPos++;
      } else if (ip.getCumulative() < 0) {
        numNeg++;
      } else {
        numNeu++;
      }
    }

    authors.add("Num Distinct User: " + authorPolarityMap.size() + "<br>"
        + "Positive: " + numPos + "<br>" + "Negative: " + numNeg + "<br>"
        + "Neutral: " + numNeu);

    return authors;
  }

  public ArrayList<String> opinionHolderStats() {

    ArrayList<String> sents = new ArrayList<String>();
    Iterator<Map.Entry<String, Comment>> it = comments.entrySet().iterator();
    int totalOpinion = 0;
    int unknown_oph = 0;
    int blank_oph = 0;
    int oph_equals_author = 0;
    int oph_is_not_author = 0;

    while (it.hasNext()) {
      Map.Entry<String, Comment> entry = it.next();
      Comment cm = entry.getValue();
      Vector<Opinion> ops = cm.getOpinions();

      for (int i = 0; i < ops.size(); ++i) {
        Opinion op = ops.get(i);
        totalOpinion++;
        if (op.getOpinionHolder().equals("")) {
          blank_oph++;
        } else if (op.isUnknownOpinionHolder()) {
          unknown_oph++;
        } else if (op.matchesWithAuthor(cm.getAuthor())) {
          oph_equals_author++;
        } else {
        	
          sents.add("<b><font color=\"Pastel Green\">"+op.getOpinionHolder() + " vs "
              + cm.getAuthor()+"</font><br>"+cm.getAuthor()+": </b>"+op.getSentence());
          oph_is_not_author++;
        }
      }
    }

    sents.add("Total num opinion: " + totalOpinion + "<br>"
        + "Unknown opinion holder: " + unknown_oph + "<br>"
        + "Blank opinion holder: " + blank_oph + "<br>"
        + "Matches with author: " + oph_equals_author + "<br>"
        + "Different from author: " + oph_is_not_author);
    return sents;
  }

  public ArrayList<String> getIssueWiseCumulativePolarity() {
    ArrayList<String> issuesInfo = new ArrayList<String>();

    HashMap<String, CumulativePolarity> issuePolarityMap = new HashMap<String, CumulativePolarity>();
    Iterator<Map.Entry<String, Comment>> it = comments.entrySet().iterator();

    while (it.hasNext()) {
      Map.Entry<String, Comment> entry = it.next();
      Comment cm = entry.getValue();

      Vector<Opinion> ops = cm.getOpinions();
      String issue = cm.getIssue();
      CumulativePolarity cp = issuePolarityMap.get(issue);
      if (cp == null) {
        cp = new CumulativePolarity();
        issuePolarityMap.put(issue, cp);
      }

      for (int i = 0; i < ops.size(); ++i) {
        Opinion op = ops.get(i);

        if (op.getPolarity() > 0) {
          cp.addPositiveComment(op.getConfidence());
        } else if (op.getPolarity() < 0) {
          cp.addNegativeComment(op.getConfidence());
        } else if (op.getPolarity() == 0) {
          cp.addNeutralComment();
        }
      }
    }

    Iterator<Map.Entry<String, CumulativePolarity>> ipm = issuePolarityMap
        .entrySet().iterator();
    int numPos = 0, numNeg = 0, numNeu = 0;
    while (ipm.hasNext()) {
      Map.Entry<String, CumulativePolarity> entry = ipm.next();
      CumulativePolarity cp = entry.getValue();

      if (cp.getCumulative() > 0) {
        numPos++;
      } else if (cp.getCumulative() < 0) {
        numNeg++;
      } else {
        numNeu++;
      }
      StringBuffer issue = new StringBuffer();

      issue.append(entry.getKey() + ";;");
      issue.append("Positive: " + cp.numPositive + ";;");
      issue.append("Negative: " + cp.numNegative + ";;");
      issue.append("Neutral: " + cp.numNeutral + ";;");
      issue.append("Cumulative: " + cp.getCumulative() + ";;");
      issue.append("Confidence: " + String.format("%.5f", cp.getCumulativeConfidence()));
      issuesInfo.add(issue.toString());
    }

    issuesInfo.add("Num Issues: " + issuePolarityMap.size() + "<br>" + "Positive: "
        + numPos + "<br>" + "Negative: " + numNeg + "<br>" + "Neutral: "
        + numNeu);

    return issuesInfo;
  }
  
  public ArrayList<String> getIssueWiseTopicList(String issue) {
    ArrayList<Feature> topicList = new ArrayList<Feature>();
    Iterator<Map.Entry<String, Comment>> it = comments.entrySet().iterator();
    while (it.hasNext()) {
      Map.Entry<String, Comment> entry = it.next();
      Comment cm = entry.getValue();      

      String currIssue = cm.getIssue();
      if (!currIssue.equals(issue)) {
        continue;
      }
      
      Vector<Opinion> ops = cm.getOpinions();
      for (int i = 0; i < ops.size(); ++i) {
        Opinion op = ops.get(i);
        ArrayList<String> opTopics = op.getTopics();
        
        for (int j = 0; j < opTopics.size(); ++j) {
          String currTopic = opTopics.get(j);
          boolean found = false;
          for (int k = 0; k < topicList.size(); ++k) {
            if (topicList.get(k).getFeature().equals(currTopic)) {
              topicList.get(k).addCount();
              found = true;
              break;
            }
          }
          
          if (!found) {
            topicList.add(new Feature(currTopic));
          }
        }
      }
    }
    
    Collections.sort(topicList);
    
    ArrayList<String> res = new ArrayList<String>();
    for (int i = 0; i < topicList.size(); ++i) {
      res.add(topicList.get(i).toString());
    }
    return res;
  }

  public ArrayList<String> showOpinionsWithPolarity(PolarityValue pv) {

    Iterator<Map.Entry<String, Comment>> it = comments.entrySet().iterator();
    ArrayList<String> sents = new ArrayList<String>();

    while (it.hasNext()) {
      Map.Entry<String, Comment> entry = it.next();

      Comment cm = entry.getValue();
      Vector<Opinion> ops = cm.getOpinions();

      for (int i = 0; i < ops.size(); ++i) {
        Opinion op = ops.get(i);
        boolean shouldShow = false;
        if (pv == PolarityValue.POSITIVE && op.getPolarity() > 0) {
          shouldShow = true;
        } else if (pv == PolarityValue.NEGATIVE && op.getPolarity() < 0) {
          shouldShow = true;
        } else if (pv == PolarityValue.NEUTRAL && op.getPolarity() == 0) {
          shouldShow = true;
        }

        if (shouldShow) {
          String sent = "<b>Author: </b>" + cm.getAuthor() + ";;"
              + "<b>Comment ID: </b>" + cm.getCommentID() + ";;"
              + "<b>Comment: </b>" + cm.getComment() + "<br>;;"
              + "<b><font color=\"Pastel Green\">Opinion: </font></b>" + op.getSentence() + ";;"
              + "<b><font color=\"Pastel Green\">Pre Sentence: </font></b>" + op.getPreSentence() + ";;"
              + "<b><font color=\"Pastel Green\">Post Sentence: </font></b>" + op.getPostSentence();
          sents.add(sent);

        }
      }
    }

    return sents;
  }

  public ArrayList<String> showCommentsWithPolarity(PolarityValue pv) {
    Iterator<Map.Entry<String, Comment>> it = comments.entrySet().iterator();
    ArrayList<String> sents = new ArrayList<String>();

    while (it.hasNext()) {
      Map.Entry<String, Comment> entry = it.next();

      Comment cm = entry.getValue();
      int p = cm.getCumulativePolarity();
      boolean shouldShow = false;
      if (pv == PolarityValue.POSITIVE && p > 0) {
        shouldShow = true;
      } else if (pv == PolarityValue.NEGATIVE && p < 0) {
        shouldShow = true;
      } else if (pv == PolarityValue.NEUTRAL && p == 0) {
        shouldShow = true;
      }

      if (shouldShow) {
        String sent = "<b>Author: </b>" + cm.getAuthor() + ";;"
            + "<b>Cumulative Polarity: </b>" + p + ";;" + "<b>Comment ID: </b>"
            + cm.getCommentID() + ";;" + "<b>Comment: </b>" + cm.getComment()
            + ";;";
        sents.add(sent);
      }
    }
    return sents;
  }

  public void showOverallCommentStats() {
    Iterator<Map.Entry<String, Comment>> it = comments.entrySet().iterator();

    int positive = 0;
    int negative = 0;
    int neutral = 0;
    int untagged = 0;

    while (it.hasNext()) {
      Map.Entry<String, Comment> entry = it.next();
      Comment cm = entry.getValue();

      if (cm.isPolaritySet()) {
        int p = cm.getCumulativePolarity();

        if (p < 0) {
          negative++;
        } else if (p > 0) {
          positive++;
        } else if (p == 0) {
          neutral++;
        }
      } else {
        untagged++;
      }
    }

    System.out.println("Positive: " + positive);
    System.out.println("Negative: " + negative);
    System.out.println("Neutral: " + neutral);
    System.out.println("Untagged: " + untagged);
  }

  public void showOverallOpinionStats() {
    Iterator<Map.Entry<String, Comment>> it = comments.entrySet().iterator();

    int positive = 0;
    int negative = 0;
    int neutral = 0;

    while (it.hasNext()) {
      Map.Entry<String, Comment> entry = it.next();
      Comment cm = entry.getValue();

      if (cm.isPolaritySet()) {
        Vector<Opinion> ops = cm.getOpinions();

        for (int i = 0; i < ops.size(); ++i) {
          int p = ops.get(i).getPolarity();

          if (p == -1) {
            negative++;
          } else if (p == 1) {
            positive++;
          } else if (p == 0) {
            neutral++;
          } else {
            System.err.println("Invalid polarity set.");
          }
        }
      }
    }

    System.out.println("Positive: " + positive);
    System.out.println("Negative: " + negative);
    System.out.println("Neutral: " + neutral);
  }

  public void parseLaw(String uri) {
    try {
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      DocumentBuilder db = dbf.newDocumentBuilder();
      Document doc = db.parse(uri);
      doc.getDocumentElement().normalize();

      NodeList nodeLst = doc.getElementsByTagName("comment");
      for (int s = 0; s < nodeLst.getLength(); s++) {

        Node fstNode = nodeLst.item(s);
        if (fstNode.getNodeType() == Node.ELEMENT_NODE) {

          Element fstElmnt = (Element) fstNode;

          NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("comment_id");
          String id = fstNmElmntLst.item(0).getChildNodes().item(0)
              .getNodeValue();

          fstNmElmntLst = fstElmnt.getElementsByTagName("comment_post_id");
          String issue = fstNmElmntLst.item(0).getChildNodes().item(0)
              .getNodeValue();
          issues_.add(issue);

          fstNmElmntLst = fstElmnt.getElementsByTagName("comment_author");
          String author = fstNmElmntLst.item(0).getChildNodes().item(0)
              .getNodeValue();

          fstNmElmntLst = fstElmnt.getElementsByTagName("comment_date");
          String date = fstNmElmntLst.item(0).getChildNodes().item(0)
              .getNodeValue();

          fstNmElmntLst = fstElmnt.getElementsByTagName("comment_parent");
          String parent = fstNmElmntLst.item(0).getChildNodes().item(0)
              .getNodeValue();

          fstNmElmntLst = fstElmnt.getElementsByTagName("comment_content");
          String comment = fstNmElmntLst.item(0).getChildNodes().item(0)
              .getNodeValue();

          comments.put(id,
              new Comment(id, comment, author, date, parent, issue));
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public void parseAppinion(String uri) {
    try {
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      DocumentBuilder db = dbf.newDocumentBuilder();
      Document doc = db.parse(uri);
      doc.getDocumentElement().normalize();

      NodeList nodeLst = doc.getElementsByTagName("opinion");

      // System.out.println(nodeLst.getLength());
      for (int s = 0; s < nodeLst.getLength(); s++) {
        Node fstNode = nodeLst.item(s);
        if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
          Element fstElmnt = (Element) fstNode;

          NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("payloads");
          Element payload = (Element) fstNmElmntLst.item(0);
          NodeList payloads = payload.getElementsByTagName("payload");

          String id = payloads.item(0).getChildNodes().item(0).getNodeValue();
          id = id.substring(12, id.length());

          if (comments.containsKey(id)) {
            Comment comment = comments.get(id);

            int p = Integer.parseInt(getStringValueFromNode(fstElmnt,
                "polarity"));
            String pre_sent = getStringValueFromNode(fstElmnt, "pre_sent");
            String post_sent = getStringValueFromNode(fstElmnt, "post_sent");
            String sent = getStringValueFromNode(fstElmnt, "sent");

            Opinion op = new Opinion(p, pre_sent, post_sent, sent);
            comment.addOpinion(op);
            op.setOpinionHolder(getStringValueFromNode(fstElmnt, "opholder"));
            op.setConfidence(getStringValueFromNode(fstElmnt, "polarity_conf"));
            op.setTopics(getChildrenValuesFromNode(fstElmnt, "topics"));
          }
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public void parseModerator(String uri) {
    try {
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      DocumentBuilder db = dbf.newDocumentBuilder();
      Document doc = db.parse(uri);
      doc.getDocumentElement().normalize();

      NodeList nodeLst = doc.getElementsByTagName("comment");
      for (int s = 0; s < nodeLst.getLength(); s++) {
        Node fstNode = nodeLst.item(s);
        if (fstNode.getNodeType() == Node.ELEMENT_NODE) {

          Element fstElmnt = (Element) fstNode;

          NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("comment_id");
          String id = fstNmElmntLst.item(0).getChildNodes().item(0)
              .getNodeValue();

          fstNmElmntLst = fstElmnt.getElementsByTagName("comment_post_id");
          String issue = fstNmElmntLst.item(0).getChildNodes().item(0)
              .getNodeValue();

          fstNmElmntLst = fstElmnt.getElementsByTagName("comment_author");
          String author = fstNmElmntLst.item(0).getChildNodes().item(0)
              .getNodeValue();

          fstNmElmntLst = fstElmnt.getElementsByTagName("comment_date");
          String date = fstNmElmntLst.item(0).getChildNodes().item(0)
              .getNodeValue();

          fstNmElmntLst = fstElmnt.getElementsByTagName("comment_parent");
          String parent = fstNmElmntLst.item(0).getChildNodes().item(0)
              .getNodeValue();

          fstNmElmntLst = fstElmnt.getElementsByTagName("comment_content");
          String comment = fstNmElmntLst.item(0).getChildNodes().item(0)
              .getNodeValue();

          modComments.put(id, new Comment(id, comment, author, date, parent,
              issue));
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public String getStringValueFromNode(Element e, String tag) {
    NodeList nl = e.getElementsByTagName(tag);

    if (nl.getLength() >= 1) {
      Node n = nl.item(0).getFirstChild();

      if (n == null)
        return "";
      return n.getNodeValue();
    } else {
      return "";
    }
  }
  
  public ArrayList<String> getChildrenValuesFromNode(Element e, String tag) {
    ArrayList<String> res = new ArrayList<String>();
    NodeList nl = e.getElementsByTagName(tag);

    if (nl.getLength() >= 1) {
      Node n = nl.item(0).getFirstChild();
      
      while (n != null) {
        Node cn = n.getFirstChild();
        
        if (cn != null) {
          res.add(cn.getNodeValue());
        }
        
        n = n.getNextSibling();
      }
    }

    return res;
  }

  /*
  public String readContent(String link) {
    StringBuffer xml = new StringBuffer();
    BufferedReader in = null;
    try {
      URL url = new URL(link);
      in = new BufferedReader(new InputStreamReader(url.openStream()));

      String line = null;
      while ((line = in.readLine()) != null) {
        xml.append(line);
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        in.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }

    return xml.toString();
  }
*/
}
